package com.example.springredirectafterlogin.config;

import com.example.springredirectafterlogin.service.impl.MySimpleAuthenticationSuccessHandler;
import com.example.springredirectafterlogin.service.impl.MyUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private MySimpleAuthenticationSuccessHandler mySimpleAuthenticationSuccessHandler;
    @Autowired
    private MyUserDetailsService myUserDetailsService;

    @Bean("authenticationManager")
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/anonymous*").anonymous()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                /*.loginPage("/login")*/
                .loginProcessingUrl("/custom/login")
                .successHandler(mySimpleAuthenticationSuccessHandler)
                /*.failureUrl("/login.html?error=true")*/
                .and()
                .logout().deleteCookies("JSESSIONID")
                .and()
                .rememberMe().key("uniqueAndSecret").tokenValiditySeconds(86400);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetailsService);
    }
}
